# safetensors库本身是为PyTorch设计的
# save_file时只能直接存储torch.Tensor

import torch
import safetensors
import safetensors.torch

class MyModule(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.net = torch.nn.Sequential(
            torch.nn.Linear(10, 10),
            torch.nn.ReLU(),
            torch.nn.Linear(10, 1)
        )

    def forward(self, x):
        return self.net(x)

net = MyModule()
safetensors.torch.save_file(net.state_dict(), 'net.safetensors')

state_dict = safetensors.torch.load_file('net.safetensors')

net2 = MyModule()
net2.load_state_dict(state_dict)

x = torch.randn(5, 10)
y = net(x)
y2 = net2(x)
print(y == y2)

z = {'value' : torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])}
safetensors.torch.save_file(z, 'z.safetensor')
loadz = safetensors.torch.load_file('z.safetensor')
print(loadz)